package com.rc.saas.mini.weixin;

import com.alibaba.fastjson.JSON;
import com.rc.saas.mini.common.constant.SessionConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * 微信配置缓存到Redis
 * @author wangzhengwei
 * @create 2021/4/29
 */
@Component
public class RedisWxConfigurationLoader {
    private static Logger logger = LogManager.getLogger(RedisWxConfigurationLoader.class);
    //对应微信服务器提供的访问令牌
    //private static final String REDIS_ACCESS_TOKEN_KEY = "saas:weixin:gxku:access_token";

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 根据originalid获取配置
     * @param originalid
     * @return
     */
    public RedisWxConfiguration get(String originalid) {
        String configuration = (String) redisTemplate.opsForValue().get(MessageFormat.format(SessionConstants.CACHE_WXCONFIG_TEMP, originalid));
        logger.warn("读取REDIS RedisWxConfiguration:{}", configuration);
        if (StringUtils.isNotBlank(configuration)) {
            return JSON.parseObject(configuration, RedisWxConfiguration.class);
        } else {
            return null;
        }
    }

    /**
     * 保存到Redis中
     * @param redisWxConfiguration
     */
    public void set(RedisWxConfiguration redisWxConfiguration) {
        logger.warn("保存configuration信息 [{}]", redisWxConfiguration.toString());
        String configuration = JSON.toJSONString(redisWxConfiguration);
        logger.warn("configuration [{}]", configuration);
        //有效期365天
        redisTemplate.opsForValue().set(MessageFormat.format(SessionConstants.CACHE_WXCONFIG_TEMP, redisWxConfiguration.getOriginalid()), configuration, 365, TimeUnit.DAYS);
    }
}
